<template>
    <div class="plot-parking">
        <!-- 筛选表单 -->
        <el-row>
            <el-col :span="24">
                <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                    <el-form-item>
                        <el-input v-model="queryForm.name" placeholder="停车场名称" />
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="queryForm.type" placeholder="停车场类型">
                            <el-option label="露天" value="1"></el-option>
                            <el-option label="地下" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button plain @click="handleReset">重置</el-button>
                        <el-button type="primary" plain @click="handleAdd">添加</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <!-- 停车场列表表格 -->
        <el-table :data="parkingList" border stripe style="width: 100%;" ref="table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="parkingId" label="停车场ID" align="center" />
            <el-table-column prop="name" label="停车场名称" align="center" />
            <el-table-column prop="type" label="停车场类型" align="center">
                <template #default="{ row }">{{ row.type === 1 ? '露天' : '地下' }}</template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(row.parkingId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="paginate.pageNum" :page-sizes="[10, 20, 30]" :page-size.sync="paginate.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" />

        <!-- 新增/编辑弹窗 -->
        <el-dialog :visible.sync="dialog.visible" width="22%">
            <template #title>{{ dialog.isEdit ? "编辑停车场" : "添加停车场" }}</template>
            <el-form ref="dialogFormRef" :model="dialog.form" :rules="dialog.rules" label-width="120px">
                <el-form-item label="停车场名称" prop="name">
                    <el-input v-model="dialog.form.name" />
                </el-form-item>
                <el-form-item label="停车场类型" prop="type">
                    <el-select v-model="dialog.form.type" placeholder="请选择">
                        <el-option label="露天" value="1"></el-option>
                        <el-option label="地下" value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { listPlot } from '@/api/plot'
import { getParkingList, addParking, updateParking, deleteParking } from '@/api/parking'
import { checkQueryInput, restForm } from '@/utils/tool'

export default {
    name: 'ParkingInfo',
    data() {
        return {
            // 锁
            isLock:false,

            parkingList: [],
            queryForm: {
                name: '',
                type: '',
                plotId: undefined
            },
            paginate: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            dialog: {
                visible: false,
                isEdit: false,
                form: {
                    parkingId: '',
                    name: '',
                    type: '',
                    plotId: undefined
                },
                rules: {
                    name: [{ required: true, message: '请输入停车场名称', trigger: 'blur' }],
                    type: [{ required: true, message: '请选择停车场类型', trigger: 'change' }]
                }
            },
            plotList: [],

            // 批量删除
            ids: [],//存储选中的所有小区ID
            single: true,//标记是否不是单选
            multiple: false//标记是否没有选中数据
        }
    },

    created() {
        const plotId = this.$store.state.plot?.currentPlot?.plotId
        if (plotId) {
            this.queryForm.plotId = plotId
            this.dialog.form.plotId = plotId
            this.getParkingList()
            this.getPlotList()
        } else {
            this.$message.warning("请先选择小区")
        }

        // 简化watch写法
        this.$watch(
            () => this.$store.state.plot?.currentPlot?.plotId,
            (newPlotId) => {
                if (newPlotId) {
                    this.queryForm.plotId = newPlotId
                    this.dialog.form.plotId = newPlotId
                    this.paginate.pageNum = 1
                    this.getParkingList()
                } else {
                    this.parkingList = []
                }
            }
        )
    },

    methods: {
        // 获取小区列表
        async getPlotList() {
            try {
                const res = await listPlot()
                this.plotList = res.rows || []
            } catch (error) {
                this.plotList = []
            }
        },

        // 获取停车场列表
        getParkingList() {
            const { total, ...rest } = this.paginate

            if (this.queryForm.type) params.type = this.queryForm.type

            return getParkingList({
                ...rest, ...this.queryForm
            }).then(res=>{
                this.parkingList = res.rows || []
                this.paginate.total = res.total || 0
            })
        },

        // 分页切换
        handleSizeChange(size) {
            this.paginate.pageSize = size
            this.getParkingList()
        },
        handleCurrentChange(page) {
            this.paginate.pageNum = page
            this.getParkingList()
        },

        // 查询
        handleQuery() {
            if (!checkQueryInput({ name: this.queryForm.name, type: this.queryForm.type })) {
                return this.$message.warning("请至少输入一项查询条件")
            }
            this.paginate.pageNum = 1
            this.getParkingList().then(() => this.$message.success("查询成功"))
        },

        // 重置
        handleReset() {
            restForm(this.$refs.queryFormRef);
            this.queryForm = {
                name: '',
                type: '',
                plotId: this.$store.state.plot.currentPlot?.plotId || undefined
            }
            this.paginate.pageNum = 1
            this.getParkingList().then(() => this.$message.success("操作成功"))
        },

        // 添加
        handleAdd() {
            const plotId = this.$store.state.plot.currentPlot?.plotId;
            if (!plotId) return this.$message.warning('请先选择小区');
            this.dialog = {
                visible: true,
                isEdit: false,
                form: { parkingId: '', name: '', type: '', plotId }
            }
        },

        // 编辑
        handleEdit(row) {
            this.dialog = {
                visible: true,
                isEdit: true,
                form: { ...row, type: String(row.type) }
            };
        },

        // 提交
        handleSubmit() {
            if(this.isLock) return
            this.$refs.dialogFormRef.validate(valid => {
                if (!valid) return;
                this.isLock=true
                const api = this.dialog.isEdit ? updateParking : addParking
                api(this.dialog.form).then(() => {
                    this.dialog.visible = false
                    this.getParkingList()
                    this.$message.success('操作成功')
                    this.isLock=false
                })
            });
        },


        // 批量删除的选中事件
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.parkingId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        // 删除
        handleDelete(parkingId) {
            const parkingIds = this.ids.length > 0 ? this.ids : [parkingId]

            const parkingIdsSrt = parkingIds.join(',')

            const count = parkingIds.length

            this.$confirm(`确定删除选中的【${count}】条停车场信息吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return deleteParking(parkingIdsSrt).then(() => {
                    this.getParkingList()
                    this.$message.success('删除成功')
                    this.$refs.table.clearSelection()
                })
            }).catch((err) => {
                console.log(err);
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.plot-parking {
    padding: 20px;
}
</style>